package com.sunny.原子性.LondAdderAndAtomicLong区别;

import com.sunny.anotation.ThreadSafe;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.concurrent.atomic.AtomicLong;

@Slf4j
@ThreadSafe
public class AtomicIntegerTest {
    // 请求总数
    public static int clientTotal = 5000;

    // 同时并发执行数量
    public static int threadTotal = 200;

    // 初始化数据
    public static AtomicLong count = new AtomicLong(0);

    public static void main(String[] args) throws InterruptedException {
        // 初始化可缓存线程池
        ExecutorService executorService = Executors.newCachedThreadPool();
        // 初始化信号量
        Semaphore semaphore = new Semaphore(threadTotal);
        // 使主线程等待子线程执行完毕再执行
        CountDownLatch countDownLatch = new CountDownLatch(clientTotal);

        for(int i = 0; i < clientTotal; i++) {
            executorService.execute(new Runnable() {
                @Override
                public void run() {
                    try {
                        semaphore.acquire();
                        add();
                        semaphore.release();
                    } catch (InterruptedException e) {
                        log.error("exception", e);
                    }
                    countDownLatch.countDown();
                }
            });
        }

        countDownLatch.await();
        executorService.shutdown();
        log.info("count:{}" + count);
    }

    private static void add() {
        count.getAndIncrement();
    }
}
